from django.contrib.auth.models import AbstractUser
from django.contrib.auth.hashers import check_password  # 新增导入
from django.db import models


class student_user(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='用户ID')  # 重命名主键字段
    username = models.CharField(max_length=50, unique=True, null=True, blank=True, verbose_name='用户名')
    password = models.CharField(max_length=128, null=True, blank=True, verbose_name='密码')
    email = models.CharField(max_length=100, null=True, blank=True, verbose_name='邮箱')
    last_login = models.DateTimeField(null=True, blank=True, verbose_name='最后登录时间')
    status = models.SmallIntegerField(null=True, blank=True, default=1, verbose_name='状态')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'student_user'  # 指定表名
        verbose_name = '用户'
        verbose_name_plural = '用户'
        indexes = [
            models.Index(fields=['username'], name='idx_student_username'),
        ]
        
    def __str__(self):
        return self.username
  # 显式指定表名
    
    # 添加Django用户模型必需属性
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []
    
    @property
    def is_anonymous(self):
        return False

    @property
    def is_authenticated(self):
        return True
    def check_password(self, raw_password):
        return check_password(raw_password, self.password)

class student_info(models.Model):
    user = models.OneToOneField(
        student_user,
        on_delete=models.CASCADE,
        related_name='profile'
    )
    id = models.IntegerField(primary_key=True, verbose_name='id')
    stu_id = models.CharField(max_length=255, verbose_name='学号')
    stu_name = models.CharField(max_length=255, verbose_name='姓名')
    seat_id = models.IntegerField(verbose_name='座号')
    stu_grade = models.IntegerField(verbose_name='年级')
    stu_college = models.CharField(max_length=255, verbose_name='学院')
    stu_class = models.CharField(max_length=255, verbose_name='班级')
    stu_gender = models.CharField(max_length=255, verbose_name='性别')
    stu_age = models.IntegerField(verbose_name='年龄')
    stu_tel = models.CharField(max_length=255, verbose_name='联系方式')
    stu_address = models.CharField(max_length=255, verbose_name='住址')
    stu_email = models.CharField(max_length=255, verbose_name='邮箱')
    hobby = models.JSONField(max_length=255, verbose_name='爱好')

    REQUIRED_FIELDS = []

    def __str__(self):
        return self.stu_name  # 返回学生的姓名作为字符串表示形式


class student_course_index(models.Model):
    course_id = models.IntegerField(primary_key=True, verbose_name='课程id')
    course_name = models.CharField(max_length=255, verbose_name='课程名称')
    course_intro = models.TextField(verbose_name='课程描述')
    course_content = models.TextField(verbose_name='课程内容')

    class Meta:
        db_table = 'student_course_index'

class student_course_chapter(models.Model):
    chapter_id = models.IntegerField(primary_key=True, verbose_name='章节id')
    course_id = models.ForeignKey(student_course_index, on_delete=models.CASCADE)
    charter_title = models.CharField(max_length=255, verbose_name='章节标题')
    order = models.PositiveIntegerField(verbose_name='排序')

    class Meta:
        db_table = 'student_course_chapter'

class student_course_KnowledgePoint(models.Model):
    course_id = models.ForeignKey(student_course_index, on_delete=models.CASCADE)
    knowledgepoint_id = models.IntegerField(primary_key=True, verbose_name='知识点id')
    chapter_id = models.ForeignKey(student_course_chapter, on_delete=models.CASCADE)
    knowledgepoint_title = models.CharField(max_length=255, verbose_name='知识点标题')
    knowledgepoint_content = models.TextField(verbose_name='知识点内容')
    order = models.PositiveIntegerField(verbose_name='排序')

    class Meta:
        db_table = 'student_course_KnowledgePoint'
class student_course_LearningProgress(models.Model):
    lp_id = models.IntegerField(primary_key=True, verbose_name='学习进度id')
    stu_id = models.ForeignKey(student_user, on_delete=models.CASCADE)
    point_id = models.ForeignKey(student_course_KnowledgePoint, on_delete=models.CASCADE)
    last_accessed = models.DateTimeField(auto_now=True)
    is_completed = models.BooleanField(default=False)

    class Meta:
        db_table = 'student_course_LearningProgress'

class Study_Note(models.Model):
    stu_id = models.ForeignKey(student_user, on_delete=models.CASCADE)
    course_id = models.ForeignKey(student_course_index, on_delete=models.CASCADE)
    note_id = models.IntegerField(primary_key=True, verbose_name='笔记id')
    note_title = models.CharField(max_length=255, verbose_name='笔记标题')
    note_content = models.TextField(verbose_name='笔记内容')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'student_study_note'

class student_course_info(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='课程id')
    name = models.CharField('课程名称', max_length=100)
    description = models.TextField('课程描述')
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'student_course_info' 

class CourseSelection(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='id')
    stu_id = models.CharField(max_length=50, verbose_name='学生ID/用户名')  # 存储用户名而非外键
    course_id = models.IntegerField(verbose_name='课程ID')  # 存储课程ID而非外键
    selected_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'student_courseselection' 
        unique_together = ('stu_id', 'course_id')

    # 兼容性方法，使模型同时支持stu_id和stu字段
    @property
    def stu(self):
        from .models import student_user
        try:
            return student_user.objects.get(username=self.stu_id)
        except:
            return None

class CourseProgress(models.Model):
    id = models.AutoField(primary_key=True)
    stu_id = models.ForeignKey(student_user, on_delete=models.CASCADE)
    course_id = models.ForeignKey(student_course_info, on_delete=models.CASCADE)
    progress = models.IntegerField(default=0)  # 百分比值
    attendance_rate = models.FloatField(default=0)  # 出勤率
    interaction_rate = models.FloatField(default=0)  # 互动率
    focus_rate = models.FloatField(default=0)  # 专注度
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'student_course_progress'
        unique_together = ('stu_id', 'course_id')
        
    # 添加别名字段，与SQL查询兼容
    @property
    def stu(self):
        return self.stu_id

class CourseCollection(models.Model):
    id = models.AutoField(primary_key=True)
    stu_id = models.ForeignKey(student_user, on_delete=models.CASCADE)
    course_id = models.IntegerField(verbose_name='课程ID', null=True, blank=True)  # 可选的课程ID字段
    title = models.CharField(max_length=255, verbose_name='收藏标题')
    content = models.TextField(verbose_name='收藏内容')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'student_course_collection'

class CourseWrongQuestion(models.Model):
    id = models.AutoField(primary_key=True)
    stu_id = models.ForeignKey(student_user, on_delete=models.CASCADE)
    course_id = models.ForeignKey(student_course_info, on_delete=models.CASCADE)
    title = models.CharField(max_length=255, verbose_name='错题标题')
    question = models.TextField(verbose_name='题目内容')
    answer = models.TextField(verbose_name='正确答案')
    wrong_answer = models.TextField(verbose_name='错误答案')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'student_course_wrong_question'

class StudentGroup(models.Model):
    group_id = models.AutoField(primary_key=True)
    group_name = models.CharField(max_length=100)
    
    class Meta:
        db_table = 'student_group'

class StudentGroupMembership(models.Model):
    id = models.AutoField(primary_key=True)
    stu_id = models.ForeignKey(student_user, on_delete=models.CASCADE, to_field='username', db_column='stu_id')
    group_id = models.ForeignKey(StudentGroup, on_delete=models.CASCADE, db_column='group_id')
    
    class Meta:
        db_table = 'student_group_membership'

class AICollection(models.Model):
    id = models.AutoField(primary_key=True)
    student_id = models.ForeignKey(student_user, on_delete=models.CASCADE)
    title = models.CharField(max_length=255, verbose_name='收藏标题')
    content = models.TextField(verbose_name='收藏内容')
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'student_ai_collections'

class StudyPlan(models.Model):
    """学生个人学习计划模型"""
    PLAN_TYPE_CHOICES = [
        ('single', '单次计划'),
        ('periodic', '周期计划')
    ]
    
    plan_id = models.AutoField(primary_key=True)
    stu_id = models.ForeignKey(student_user, on_delete=models.CASCADE, verbose_name='学生')
    plan_name = models.CharField(max_length=100, verbose_name='计划名称')
    plan_date = models.DateField(verbose_name='计划日期')
    plan_type = models.CharField(max_length=10, choices=PLAN_TYPE_CHOICES, default='single', verbose_name='计划类型')
    start_time = models.TimeField(verbose_name='开始时间')
    end_time = models.TimeField(verbose_name='结束时间')
    plan_content = models.TextField(verbose_name='计划内容')
    
    # 周期计划特有字段
    cycle_value = models.IntegerField(null=True, blank=True, verbose_name='周期数值')
    cycle_unit = models.CharField(max_length=10, null=True, blank=True, verbose_name='周期单位')
    start_date = models.DateField(null=True, blank=True, verbose_name='开始日期')
    end_date = models.DateField(null=True, blank=True, verbose_name='结束日期')
    
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'student_study_plan'
        verbose_name = '学习计划'
        verbose_name_plural = verbose_name
        ordering = ['plan_date', 'start_time']
    
    def __str__(self):
        return f"ID:{self.stu_id}的计划：{self.plan_name}"

# 知识图谱相关模型
class KnowledgeGraphNode(models.Model):
    id = models.AutoField(primary_key=True)
    course_id = models.ForeignKey(student_course_info, on_delete=models.CASCADE)
    node_id = models.CharField(max_length=50, verbose_name='节点ID')
    label = models.CharField(max_length=255, verbose_name='节点标签')
    level = models.IntegerField(default=1, verbose_name='节点层级')
    content = models.TextField(null=True, blank=True, verbose_name='节点内容')
    type = models.CharField(max_length=50, default='default', verbose_name='节点类型')
    
    class Meta:
        db_table = 'student_knowledge_graph_node'
        unique_together = ('course_id', 'node_id')
        
    def __str__(self):
        return f"{self.course_id.name} - {self.label}"
        
class KnowledgeGraphEdge(models.Model):
    id = models.AutoField(primary_key=True)
    course_id = models.ForeignKey(student_course_info, on_delete=models.CASCADE)
    source = models.CharField(max_length=50, verbose_name='源节点ID')
    target = models.CharField(max_length=50, verbose_name='目标节点ID')
    relation = models.CharField(max_length=50, null=True, blank=True, verbose_name='关系类型')
    
    class Meta:
        db_table = 'student_knowledge_graph_edge'
        unique_together = ('course_id', 'source', 'target')
        
    def __str__(self):
        return f"{self.source} -> {self.target}"
